<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="门店名称" prop="placePointName">
        <el-input v-model="queryParams.placePointName" placeholder="请输入内容" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="药品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入内容" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="患者名称" prop="patientName">
        <el-input v-model="queryParams.patientName" placeholder="请输入内容" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="状态" prop="status">-->
      <!--        <el-select v-model="queryParams.status" placeholder="请选择状态">-->
      <!--          <el-option v-for="dict in dict.type.sys_lq_state" :key="dict.value" :label="dict.label"-->
      <!--            :value="dict.value"></el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="领用时间" prop="signTime">
        <el-date-picker v-model="queryParams.signTime" value-format="yyyy-MM-dd" :picker-options="pickerOptions"
          type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" align="right">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" class="add" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" class="delBtn" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-download" type="primary" class="delBtn" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
    </el-row> -->
    <el-table ref="table" :key="tableKey" v-loading="loading" :data="roleList" style="margin-top: 20px">

      <el-table-column label="门店名称" prop="placePointName" />
      <el-table-column label="药品名称" prop="goodsName" />
      <el-table-column label="门店操作系统网址" prop="operateUrl">
        <template slot-scope="scope">
          <a :href="scope.row.operateUrl" target="_blank">{{ scope.row.operateUrl }}</a>
        </template>
      </el-table-column>
      <el-table-column label="规格" prop="goodsType" />
      <el-table-column label="厂家" prop="factoryName" />
      <el-table-column label="领用时间" prop="receiveTime" />
      <el-table-column label="领药政策" prop="aidProjectUrl">
        <template slot-scope="scope">
          <a :href="scope.row.aidProjectUrl" target="_blank">{{ scope.row.aidProjectUrl }}</a>
        </template>
      </el-table-column>
      <el-table-column label="领取数量" prop="receiveNum" />
      <el-table-column label="患者名称" prop="patientName" />
      <el-table-column label="患者手机" prop="patientPhone" />
      <el-table-column label="患者身份证" prop="patientIdentity" />
      <el-table-column label="操作人" prop="createByName" />
      <el-table-column label="下次购买时间" prop="nextTime" />
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <div class="img_box">
            <img v-for="(item, index) in scope.row.imgUrls" :key="index" :src="'/api' + item" alt="" class="img" />
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column label="状态" align="center">-->
      <!--        <template slot-scope="scope">-->
      <!--          <dict-tag :options="dict.type.sys_lq_state" :value="scope.row.status" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button v-hasPermi="['bus:receive:downloadZip']" type="text" class="btnText"
            @click="handleDwon(scope.row)">下载全部图片</el-button>

          <!--          <el-button v-hasPermi="['bus:receive:update']" class="btnText" type="text" @click="handleDelete(scope.row)"-->
          <!--            v-if="scope.row.status == 0">完成</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getListData" />

  </div>
</template>

<script>
  import {
    getList,
    completeData,
    downData,
    receiveExport
  } from "@/api/medicineManage/indexs";
  import { getToken } from "@/utils/auth";
  import { getUserProfile } from "@/api/system/user";
  export default {
    name: "Role",
    dicts: ["sys_lq_state"],
    data() {
      return {
        dialogVisible: false,
        dialogImageUrl: "",
        uploadUrl:
          process.env.VUE_APP_BASE_API + "/common/uploadPc/goodsRegister", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken(),
        },
        pickerOptions: {
          shortcuts: [
            {
              text: "最近一周",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近一个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit("pick", [start, end]);
              },
            },
            {
              text: "最近三个月",
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                picker.$emit("pick", [start, end]);
              },
            },
          ],
        },
        user: {},
        fileList: [],
        title: "添加",
        open: false,
        tableKey: 0,
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 10,
        // 角色表格数据
        roleList: [],
        // 查询参数
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          phone: "",
          signTime: "",
        },

        systemList: [],
      };
    },
    created() {
      this.getListData();
      getUserProfile().then((res) => {
        this.user = res.data;
      });
    },
    methods: {
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
        console.log(file.url);
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
        const isJPG = type.includes(file.type);
        // 检验文件格式
        if (!isJPG) {
          this.$message.error(`图片格式错误!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 < 500;
          if (!isLt) {
            this.$message.error(`上传文件大小不能超过 500 KB!`);
            return false;
          }
        }
        return true;
      },
      handleRemove(file, fileList) {
        console.log(file);
        const list = this.addForm.imageUrls.filter(
          (item) => item !== file.response.fileName
        );
        this.addForm.imageUrls = list;
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
          } 个文件`
        );
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      handleUploadSuccess(res, file) {
        // 如果上传成功
        if (res.code == 200) {
          this.addForm.imageUrls.push(res.fileName);
        } else {
          this.$message.error("图片上传失败");
        }
      },
      /** 查询列表 */
      getListData() {
        this.loading = true;
        getList({
          ...this.queryParams,
          startDate: this.queryParams.signTime[0],
          endDate: this.queryParams.signTime[1],
        }).then((response) => {
          this.roleList = response.data.records;

          for (let i = 0; i < this.roleList.length; i++) {
            let row = this.roleList[i]

            this.roleList[i].factoryName = row.factoryName.join('、')
            this.roleList[i].goodsType = row.goodsType.join('、')
            this.roleList[i].goodsName = row.goodsName.join('、')
            this.roleList[i].receiveNum = row.receiveNum.join('、')

            if (row.aidProjectUrl && row.aidProjectUrl.length > 0) this.roleList[i].aidProjectUrl = row.aidProjectUrl.join('、')
            this.roleList[i].operateUrl = row.operateUrl.join('、')

          }


          this.total = response.data.total || 0;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.$nextTick(() => {
          this.getListData();
        });
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.pageNum = 1;
        this.resetForm("queryForm");
        this.handleQuery();
      },


      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.addForm = {
          phone: "",
          signTime: "",
          description: "",
          imageUrls: [],
          remark: "",
        };
        this.fileList = [];
        this.resetForm("addForm");
      },
      /** 按钮操作 */
      handleDelete(row) {
        completeData(row).then(res => {
          this.$modal.msgSuccess("处理成功");
          this.getListData();
        })
      },
      handleDwon(row) {
        // this.download("/bus/receive/batchDownload/" + row.id, {});
        downData(row).then(res => {
          let blob = new Blob([res], { type: 'application/zip' })
          let url = window.URL.createObjectURL(blob)
          const link = document.createElement('a') // 创建a标签
          link.href = url
          link.download = row.goodsName // 重命名文件
          link.click()
          URL.revokeObjectURL(url) // 释放内存
        })


      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["addForm"].validate((valid) => {
          if (valid) {
            if (this.addForm.imageUrls.length == 0)
              return this.$message.error("请上传图片");
            if (this.addForm.id) {
              editData({
                ...this.addForm,
                contactByName: this.user.nickName,
              }).then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getListData();
              });
            } else {
              addData({
                ...this.addForm,
                contactByName: this.user.nickName,
              }).then((response) => {
                this.$modal.msgSuccess("添加成功");
                this.open = false;
                this.getListData();
              });
            }
          }
        });
      },
      // 导出列表
      handleExport() {
        this.loading = true;

        receiveExport({
          ...this.queryParams,
          startDate: this.queryParams.signTime[0],
          endDate: this.queryParams.signTime[1],
        }).then((res) => {
          if (!res) return
          const link = document.createElement('a')
          let blob = new Blob([res], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', `慈善赠药管理-领用记录_${this.format(Date.now())}.xlsx`)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          this.loading = false;
          this.$message({
            message: '下载成功',
            type: 'success'
          });
          
        });
      },
      // 时间格式化
      format(date) {
        let time = new Date(date)
        const year = time.getFullYear();
        const month = (time.getMonth() + 1).toString().padStart(2, '0');
        const day = time.getDate().toString().padStart(2, '0');
        // 获取小时（0-23）
        const hours = time.getHours().toString().padStart(2, '0');
        // 获取分钟（0-59）
        const minutes = time.getMinutes().toString().padStart(2, '0');
        const formattedDate = `${year}-${month}-${day} ${hours}-${minutes}`;
        return formattedDate
      },
    },
  };
</script>
<style lang="scss" scoped>
  .imgprev {
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      max-width: 100%;
      max-height: 100%;
      display: block;
    }
  }

  .footerForm {
    margin-left: 200px;
  }

  .formBox {
    width: 600px;
    margin-top: 40px;
  }

  .btnText {
    color: #0052d9 !important;
  }

  .dialogForm {
    ::v-deep .el-form-item {
      margin-bottom: 10px;
    }

    ::v-deep.el-form--label-top .el-form-item__label {
      padding: 0;
    }
  }

  .add {
    background: #0052d9;
    color: #fff;
    border: none;
  }

  .delBtn {
    background: #e7e7e7;
    color: #000;
    border: none;
  }

  .open {
    width: 52px;
    height: 32px;
    background: #e3f9e9;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #2ba471;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #2ba471;
  }

  .close {
    width: 52px;
    height: 32px;
    background: #d8d8d8;
    border-radius: 3px 3px 3px 3px;
    border: 1px solid #767676;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 400;
    font-size: 14px;
    color: #767676;
  }

  .statusBox {
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .status_div {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 66px;
    height: 32px;
    background: #ffffff;
    border-radius: 3px;
    border: 1px solid #e7e7e7;
    font-size: 14px;
    background: #f3f3f3;
    color: rgba(0, 0, 0, 0.9);
    line-height: 1;

    &.jxz {
      background: #f2f3ff;
      border: 1px solid #0052d9;
      color: #0052d9;
    }

    &.ywc {
      background: #e3f9e9;
      border: 1px solid #2ba471;
      color: #2ba471;
    }
  }

  .img {
    width: 38px;
    height: 38px;
  }

  .img_box {
    display: flex;
    justify-content: center;
    gap: 10px;
  }
</style>